#!/sbin/openrc-run
# Copyright 1999-2018 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

userpc="yes"
retry_count="40"
retry_delay="0.5"

bin=/usr/sbin/openl2tpd
pid=/var/run/openl2tpd.pid
[ -z "${OPENL2TPD_CONFIG_FILE}" ] && OPENL2TPD_CONFIG_FILE="/etc/openl2tpd.conf"

depend() {
    need net
    [ "${userpc}" = "yes" ] && need portmap
    use dns ipsec racoon
}

check_module () {
    if ! [ -f /proc/net/pppol2tp ]; then
    ebegin "Loading l2tp module"
    # try both new and old module names
	modprobe l2tp_ppp 2>/dev/null || modprobe pppol2tp 2>/dev/null
    eend $? 
    fi
}

start() {
    check_module
    ebegin "Starting openl2tpd"
    # if rpc is enabled do not read config file by daemon (has bugs),
    # but read by l2tpconfig instead
    if [ "${userpc}" = "yes" ]; then 
        conf="/dev/null"
    else
        conf="${OPENL2TPD_CONFIG_FILE}"
    fi

    start-stop-daemon --start --quiet --exec ${bin} --pidfile ${pid} \
        -- -c "$conf" ${OPENL2TPDARGS}

    # it is possible to not to have config at all
    if [ "${userpc}" = "yes" ] && [ -r "${OPENL2TPD_CONFIG_FILE}" ]; then
        # on system startup it may take some time to load daemon
        local i=0;
        while [ $i -lt $retry_count ]; do
            l2tpconfig config restore file="${OPENL2TPD_CONFIG_FILE}" >/dev/null 2>&1
            retcode=$?
            [ ${retcode} = 0 ] && break
            i=$((i+1))
            sleep $retry_delay
        done
    fi
    eend $retcode
}

stop() {
    local rc
    ebegin "Stopping openl2tpd"
    start-stop-daemon --stop --quiet --exec ${bin} --pidfile ${pid}
    rc=$?

    if [ ${RC_CMD} = "restart" ]; then
        einfo "sleeping for server to finalize connections"
        sleep 2
    fi

    eend ${rc}
}
